package org.alex.nettychat.netty.custom.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import org.alex.nettychat.netty.custom.protocol.SendToGroupRequestPacket;
import org.alex.nettychat.netty.custom.protocol.SendToGroupResponsePacket;
import org.alex.nettychat.netty.custom.session.Session;
import org.alex.nettychat.netty.custom.utils.SessionUtil;


/**
 * 创建群里请求
 *
 * @author : alex
 */
public class SendToGroupRequestHandler extends SimpleChannelInboundHandler<SendToGroupRequestPacket> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, SendToGroupRequestPacket sendToGroupRequestPacket) throws Exception {
        Integer groupId = sendToGroupRequestPacket.getGroupId();
        String msg = sendToGroupRequestPacket.getMsg();

        Session session = SessionUtil.getSession(ctx.channel());

        ChannelGroup group = SessionUtil.getChannelGroup(groupId);
        SendToGroupResponsePacket responsePacket = new SendToGroupResponsePacket();
        responsePacket.setMsg(msg);
        responsePacket.setSendUserId(session.getUserId());
        responsePacket.setSendUserName(session.getUserName());
        responsePacket.setGroupId(groupId);
        group.writeAndFlush(responsePacket);
    }
}
